-- print("________2222222222222222", type(hf_setenv))


local _ENV,_START = hf_setenv('msg_handler',true)


local skynet = require "skynet"
local mongo = require "skynet.db.mongo"
local proxypack = require "proxypack"
local server_def = require "server_def"
local constant = require "constant"
local utils = require "utils"
local reason = require "reason"
local error_code = require "error_code"
local cjson = require "cjson"
local sharedata  = require "skynet.sharedata"
local util = require "util"
local md5 = require "md5"
local math_floor  = math.floor
local math_random = math.random

local table_insert = table.insert







-- local COLL_MT = {
--     __index = function(t, k)
--         return function(t, ...)
--             return xpcall(
--                 function(t, ...)
--                     return t.coll[k](t.coll, ...)
--                 end, debug.traceback, t, ...)
--         end
--     end
-- }



-- local seq_coll
-- local business_coll

-- local function next_seq(seq_name)
--     local ok, res = seq_coll:findAndModify({query={_id=seq_name},
--                                             update={["$inc"]={seq=1}}})

--     if not ok or not res or not res["value"] or not res["value"]["seq"] then
--         return false, 0
--     end

--     return true, res["value"]["seq"]
-- end

-- local function save_business_info(business_id, business_info_list)
--     dbglog("save_business_info:", business_id, business_info_list)
--     local ok = business_coll:insert({business_id=business_id, business_info_list=business_info_list})
--     return ok
-- end

-- local function get_business_info(business_id)
--     dbglog("get_business_info:", business_id)
--     local ok, res = business_coll:findOne({business_id=business_id}, {_id=false})
--     return ok, res
-- end

-- local function remove_business_info(business_id)
--     dbglog("remove_business_info:", business_id)
--     local ok = business_coll:delete({business_id=business_id})
--     return ok
-- end




function init()
    global_configs = nil
    closing_sever = false
    agents = {}
    uid_session_map = {}

    hf_set_sentinel_end(_ENV)
end






local CMD = {}

-- function CMD.send_notify(uid_list, notify_type, notify_info, send_msg)
--     dbglog(string.format("send_notify uid_list(%s) notify_type(%d) notify_info(%s) send_msg(%s)",
--     	tostring_r(uid_list), notify_type, tostring_r(notify_info), tostring_r(send_msg)))

--     local ok, business_id = next_seq("business_seq")
--     if not ok then
--     	errlog("next_seq error")
--         return skynet.retpack(error_code.HALL_DB_ERROR)
--     end

--     local notify = {type=notify_type, notice=notify_info, business_id=business_id}
--     local encoded_notice = cjson.encode(notify_info)

--     local business_info_list = {}
--     for _, v in pairs(uid_list) do
--         local ok, notice_id = R().exdbsvr({key=v}):
--             call('.notice_mgr', 'add_notice', v, notify)

--         if ok then
--             table_insert(business_info_list, {uid = v, notice_id = notice_id})

--             R().hallsvr({key=v}):
--                 send('.msg_handler', 'toagent', v, 'send_to_gateway', 'hall.NTF_RED_POINTS',
--                      {module_list = {constant.MODULE_DEF.MAIL}})

--             if send_msg then
--                 local notice = {
--                     type=notify_type,
--                     notice=encoded_notice,
--                     business_id=business_id,
--                     id = notice_id,
--                 }
--                 R().hallsvr({key=v}):
--                     send('.msg_handler', 'toagent', v, 'send_notify', 'common.GENERAL_NOTICE', notice)
--             end
--         else
--         	errlog(string.format("call exdbsvr error ok(%s)", tostring_r(ok)))
--         end
--     end

--     local ok = save_business_info(business_id, business_info_list)
--     if not ok then
--         return skynet.retpack(error_code.HALL_DB_ERROR)
--     end

--     return skynet.retpack(0)
-- end

-- function CMD.remove_notify(business_id)
--     dbglog("remove_notify:", business_id)

--     local ok, res = get_business_info(business_id)
--     if not ok or not res then
--         return skynet.retpack(error_code.HALL_DB_ERROR)
--     end

--     for _, v in pairs(res.business_info_list) do
--         local ok, notice_id = R().exdbsvr({key=v.uid}):
--             send('.notice_mgr', 'del_notice', v.uid, v.notice_id)
--     end

--     local ok = remove_business_info(business_id)
--     if not ok then
--         return skynet.retpack(error_code.HALL_DB_ERROR)
--     end

--     return skynet.retpack(0)
-- end

function CMD.data(game_session,data,uid,ip,account_id)
	print('got data',game_session,#data,uid,ip)
	if closing_sever then
		errlog('hallsvr is closing now!!!',uid)
		return
	end

	local agent = agents[uid]
	if not agent then
		print("New client from : ",util.inet_ntoa(ip),uid,game_session)
		agents[uid] = 0
		agent = skynet.newservice("agent")
		agents[uid] = agent
		skynet.call(agent, "lua", "start", {
			fd = game_session,
			uid = uid,
			msg_handler = skynet.self(),
			ip = ip,
            account_id = account_id,
		})
		assert(not uid_session_map[uid])
		uid_session_map[uid] = game_session
	elseif agent == 0 then
		errlog('sending request too fast,service is not created completely yet')
		return
	end

	local origin_session = assert(uid_session_map[uid])
	if origin_session == 0 then
		errlog(uid,'intersected data when insteading')
		return
	end

	--假如不是同一个会话，则需要新会话覆盖旧会话
	if game_session ~= origin_session then
		dbglog('now instead uid',uid,origin_session,game_session)
		uid_session_map[uid] = 0
		if not skynet.call(agent, "lua", "instead", game_session,ip) then
			--还回去
			uid_session_map[uid] = origin_session
			errlog(uid,'failed to instead',game_session)
			return
		end
		assert(uid_session_map[uid] == 0,string.format('inconsistency state %d',uid))
		uid_session_map[uid] = game_session
	end

	skynet.send(agent,'client',data)
end

function CMD.close(uid,game_session,reason)
	print(game_session,'closed','reason',reason)
	local agent = agents[uid]
	if not agent then
		errlog('could not find game session',uid,game_session)
		return
	end

	local curr_session = assert(uid_session_map[uid])
	if game_session ~= curr_session then
		errlog('game_session not match uid session',game_session,curr_session)
		return
	end

	skynet.send(agent,'lua','disconnect',reason)
	uid_session_map[uid] = -1
end

local function print_player_num()
	while true do
		local online_count = 0
		for uid,_ in pairs(agents) do
			online_count = online_count + 1
		end
		--dbglog('now player num',online_count)
        billlog({op="online_player",online_count = online_count})
		skynet.sleep(500)
	end
end

function CMD.start()
	print('start....')

    -- local db_conf = {host=skynet.getenv("mongodb_host"),
    --                  port=skynet.getenv("mongodb_port")}
    -- dbglog("mongodb_host:", db_conf.host, "mongodb_port:", db_conf.port)
    -- local db_conn = require("mongo_pool").new(db_conf):get_conn_from_pool()
    -- seq_coll = setmetatable({coll=db_conn["hall"]["seqs"]}, COLL_MT)
    -- business_coll = setmetatable({coll=db_conn["hall"]["business_info"]}, COLL_MT)

	skynet.fork(print_player_num)
	skynet.retpack(true)
end

function CMD.on_agent_exit(uid,source)
	local addr = assert(agents[uid],'could not find agent ' .. uid)
	assert(addr == source,string.format('%s ~= %s',addr,source))
	assert(uid_session_map[uid],'no such session map ' .. uid)

	agents[uid] = nil
	uid_session_map[uid] = nil
end

function CMD.get_agent(uids)
	if type(uids) == 'table' then
		local rets = {}
		for _,uid in pairs(uids) do
			rets[uid] = agents[uid]
		end
		return skynet.retpack(rets)
	elseif type(uids) == 'number' then
		local uid = uids
		return skynet.retpack(agents[uid])
	else
		return skynet.retpack(nil)
	end
end

function CMD.get_agent_count()
	local online_count = 0
	for uid,_ in pairs(agents) do
		online_count = online_count + 1
	end
	return skynet.retpack(online_count)
end

function CMD.get_all_agent()
	return skynet.retpack(agents)
end

function CMD.toagent(uid,...)
	local agent = agents[uid]
	if not agent then
		errlog('could not find player',uid)
		return
	end

	skynet.send(agent,'lua',uid,...)
end

function CMD.callagent(uid, ...)
	local agent = agents[uid]
	if not agent then
		errlog('could not find player',uid)
		return skynet.retpack(nil)
	end

	local data = skynet.call(agent,'lua',uid,...)
	skynet.retpack(data)
end

function CMD.new_platform_mail(mail_type,range)
    print("new_platform_mail=========",mail_type,range)
	if mail_type == constant.PLATFORM_MAIL_TYPE_ALL then
		for uid,agent in pairs(agents) do
			skynet.send(agent,'lua',uid,'new_platform_mail')
		end
	elseif mail_type == constant.PLATFORM_MAIL_TYPE_SPEC then
		local uid_list = utils.str_split(range,",")
		if not uid_list then
			errlog("new_platform_mail uid_list error")
			return
		end
		for id,uid in pairs(uid_list) do
			uid = tonumber(uid)
			if agents[uid] then
				skynet.send(agents[uid],'lua',uid,'new_platform_mail')
			end
		end
	end
end

function CMD.notify_modify_mail(range)
	print("notify_modify_mail1111111111111111",tostring_r(range))
	if not range then
		return
	end

	local uid_list = utils.str_split(range,",")
	for id,uid in pairs(uid_list) do
		uid = tonumber(uid)
		if agents[uid] then
			skynet.send(agents[uid],'lua',uid,'notify_modify_mail')
		end
	end
end

function CMD.kick_player(uid, reason)
    print("_________kick_player___________",uid, reason)
	if agents[uid] then
		skynet.send(agents[uid],'lua','kick_player', reason)
	end
end

-- function CMD.kick_player(account_id, reason)
--     if agents[uid] then
--         skynet.send(agents[uid],'lua','kick_player', reason)
--     end
-- end

function CMD.common_post(uid,url,data)
    if agents[uid] then
        skynet.send(agents[uid],'lua','common_post',url,data)
    end
end

local function common_post_web(uid,url,data)

    local effect_time = util.get_now_time()
    local exheader = {uid=uid,time=effect_time,channel = data.channel}
    local ok,status,body = R().accountsvr({rand=true}):call('.web_proxy','web_post',url,cjson.encode(data),exheader)
    if not ok then
        errlog('failed to common_post========',uid, url)
        return -1
    end

    -- local effect_time = util.get_now_time()
    -- local INTERNAL_KEY = "e948afae5761018e7af958e0a8bd675a"
    -- local sign = md5.sumhexa(string.format("%d%d%s",uid,effect_time,INTERNAL_KEY))
    -- local headers = { sign=sign,uid=uid,time=effect_time,channel = data.channel}
    -- headers['content-type'] = 'application/json'
    -- local EXCHANGE_WEBSERVER_URL = skynet.getenv("EXCHANGE_WEBSERVER_URL") or "192.168.1.121:8101"

    -- local ok,status,body = R().accountsvr({rand=true}):call('.web_proxy','web_post',EXCHANGE_WEBSERVER_URL,url,headers,cjson.encode(data))
    -- if not ok then
    --     errlog(uid,'common_post_web ========',url)
    --     return {status = -1,body = body}
    -- end

    print(uid,url,"common_post_web", data)
    return {status = status,body = body}
end

local ADD_URL  = constant.STOCK_ADD_URL
local EDIT_URL = constant.STOCK_EDIT_URL

--已废弃
function CMD.exhcange_coins(uid,coins)
    local personal_control = global_configs.personal_control or {}
    local reduce_coins_rate  = (personal_control["exchange_rate"] or 0) / 100
    if reduce_coins_rate == 0 then return end
    local reduce_weight_rate = (personal_control["exchange_weight"] or 0) / 100
    local reduce_coins  = math_floor(coins * reduce_coins_rate)
    local reduce_weight = math_floor(coins/100 * reduce_weight_rate)
    if reduce_coins_rate == 0 then
        return
    end

    local ok,ret = R().basesvr({key = uid}):call('.msg_handler','reduce_control_coins_weight',uid,reduce_coins,reduce_weight,reason.CHARGE_RETRUN)
    print("exhcange_coins======22222233333333",ok,tostring_r(ret))
    if ok and ret then
        if ret.add then
            local xcoins = -(reduce_coins / 100)
            if xcoins < 0 then
                local info = {
                    control_amount  = -(reduce_coins / 100),
                    weights = reduce_weight,
                    creation_type = "吃分控制",
                }
                common_post_web(uid,ADD_URL,info)
            end
        else
            local info = {
                control_amount  = ret.curr_control_coins / 100,
                weights = ret.curr_control_weight,
                creation_type = "吃分控制",
            }
            common_post_web(uid,EDIT_URL,info)
        end
    end
end

--已废弃
function CMD.frist_charge_rate(uid,paid_amount,charge_count)
    print("frist_charge_rate11111111",uid,paid_amount,charge_count)

    local personal_control = global_configs.personal_control or {}
    local add_coins_rate  = (personal_control["charge_rate"] or 0) / 100
    local add_weight_rate = (personal_control["charge_weight"] or 0)
    if charge_count and charge_count == 1 then --首冲
        add_coins_rate  = (personal_control["frist_charge_rate"] or 0) / 100
        add_weight_rate = (personal_control["frist_charge_weight"] or 0)
        -- R().activitysvr(1):send('.activity_mgr','check_first_charge',uid,paid_amount)
    end
    if add_coins_rate == 0 then
        return
    end

    local add_coins = math_floor(paid_amount * add_coins_rate)
    local add_weight = add_weight_rate
    local ok,ret = R().basesvr({key = uid}):call('.msg_handler','add_control_coins_weight',uid,add_coins,add_weight,reason.CHARGE_RETRUN)
    print("add_paid_product======22222233333333",ok,tostring_r(ret))
    if ok and ret then
        if ret.add then
            local xcoins = add_coins / 100
            if xcoins > 0 then
                local info = {
                    control_amount  = xcoins,
                    weights = add_weight,
                    creation_type = charge_count == 1 and "首冲返水" or "充值返水",
                }
                common_post_web(uid,ADD_URL,info)
            end
        else
            local info = {
                control_amount  = ret.curr_control_coins / 100,
                weights = ret.curr_control_weight,
                creation_type = charge_count == 1 and "首冲返水" or "充值返水",
            }
            common_post_web(uid,EDIT_URL,info)
        end
    end
end

--已废弃
function CMD.is_new_player(uid)
    --发送消息去PHP
    local personal_control = global_configs.personal_control or {}
    local add_coins  = (personal_control["new_player_rate"] or 0) / 100
    local add_weight = personal_control["new_player_weight"] or 0
    print("is_new_player===========",add_weight)
    if add_coins > 0 then
        local info = {control_amount  = add_coins,weights = add_weight,creation_type = "新增奖励"}
        common_post_web(uid,ADD_URL,info)
    end
end

--已废弃
function CMD.start_by_lucky(uid)
    local ok,curr_coins = R().basesvr({key=uid}):call('.msg_handler','get_coins',uid)
    print("start_by_lucky=============1111",ok,curr_coins)
    if not ok or not curr_coins then
        return
    end

    if not agents[uid] then
        return
    end

    local user_guide_trigger = global_configs.user_guide_tigger
    if not user_guide_trigger or not user_guide_trigger.gm_rate then
        return
    end

    local user_data = skynet.call(agents[uid],'lua','get_user_data',uid)
    print("start_by_lucky=============2222",user_data.user_guide_gm_time)
    if util.get_now_time() - user_data.user_guide_gm_time <= (user_guide_trigger.gm_limit *60*60) then
        return
    end

    if math_random(1,100) <= user_guide_trigger.gm_rate then --触发
        local personal_control = global_configs.personal_control or {}
        local add_coins  = math_floor((personal_control["user_guide_rate"] or 0)/100 * curr_coins)
        local add_weight = personal_control["user_guide_weight"] or 0
        local ok,ret = R().basesvr({key = uid}):call('.msg_handler','add_control_coins_weight',uid,add_coins,add_weight,reason.LUCKY)
        print("start_by_lucky=============3333",ok,tostring_r(ret))
        if not ok or not ret then
            return
        end
        skynet.send(agents[uid],'lua','update_user_guide_gm_time')

        local data = {control_amount =  math_floor(add_coins/100),weights = add_weight,creation_type = "用户引导"}
        if not ret.add then
            data.control_amount = math_floor(ret.curr_control_coins/100)
            data.weights = ret.curr_control_weight
            return common_post_web(uid,EDIT_URL,data)
        end

        return common_post_web(uid,ADD_URL,data)
    end
end

function CMD.get_today_continue_time(uid)
    if not agents[uid] then
        return
    end

    local continue_time = skynet.call(agents[uid],'lua','get_today_continue_time',uid)
    skynet.retpack(continue_time)
end

function CMD.check_lucky_tigger(uid,game_type,init_coins)
    print("check_lucky_tigger==========",uid,game_type,init_coins)
    if not agents[uid] then
        return
    end

    local user_guide = global_configs.user_guide
    local user_guide_trigger = global_configs.user_guide_tigger
    local user_guide_introduce = global_configs.user_guide_introduce
    if not user_guide or not user_guide_trigger or not user_guide[game_type] then
        errlog("check_lucky_tigger==config==error")
        return
    end

    print("check_lucky_tigger==========1111",uid,game_type,init_coins,user_guide_trigger.trigger_rate,tostring_r(user_guide_trigger))
    if math_random(1,100) > (user_guide_trigger.trigger_rate or 0) then
        return
    end

    local user_data = skynet.call(agents[uid],'lua','get_user_data',uid)
    print("check_lucky_tigger==========2222",user_data.user_guide_time)
    if util.get_now_time() - user_data.user_guide_time <= (user_guide_trigger.trigger_limit * 60) then
        return
    end

    local ok,curr_coins = R().basesvr({key=uid}):call('.msg_handler','get_coins',uid)
    print("check_lucky_tigger==========2222",ok,curr_coins)
    if not ok or not curr_coins then
        return
    end

    local config = {}
    local win_coins = curr_coins - init_coins
    print("check_lucky_tigger==========3333",uid,win_coins)
    if win_coins > 0 then
        config = user_guide_introduce.win_introduce
    end
    if win_coins < 0 then
        config = user_guide_introduce.lose_introduce
    end
    if not config or not next(config) then
        return
    end

    local rand_index = math_random(1,#config)
    local data = {
        cur_lucky  = config[rand_index].name,
        lucky_star = (config[rand_index].star or 0)*10,
        lucky_introduce = config[rand_index].introduce,
        lucky_effect = config[rand_index].effect,
        recommend_game_type = user_guide[game_type]
    }
    skynet.send(agents[uid],'lua','lucky_tigger',data)
end

-- function CMD.notify_all_agent(result,is_notice)
--     print("======notify_all_agent")
-- 	for uid,agent in pairs(agents) do
--         if agent ~= 0 then
--             skynet.send(agent,'lua',uid,'send_opration_message',result,is_notice)
--         end
-- 	end
-- 	--if is_cache then
-- 	--	skynet.send('.opration_message_mgr','lua','add_messages',messages)
-- 	--end
-- end

--广播消息
function CMD.broadcast_msg(msgname,msg)
    local msg_pack = utils.encode_msg(msgname,msg)
    if not msg_pack then
        errlog("broadcast_msg --> error",msgname,tostring_r(msg))
        return false
    end

    local gateway_list = {}
    for uid,client_fd in pairs(uid_session_map) do
        if client_fd > 0 then
            local gateway_id = client_fd >> 31
            local t = gateway_list[gateway_id]
            if not t then 
                t = {}
                gateway_list[gateway_id] = t
            end

            table_insert(t,client_fd)
        end
    end

    for gateway_id,client_list in pairs(gateway_list) do
        utils.broadcast_msg(gateway_id,client_list,msg_pack)
    end
    -- for _,agent in pairs(agents) do
    --  if agent ~= 0 then
    --      skynet.send(agent,'lua','send_broadcast_msg',msg_pack)
    --  end
    -- end
    return true
end

--给指定玩家发个消息
function CMD.send_msg(uid, msgname, msg)
    local agent = agents[uid]
    dbglog("send_msg=111==",uid, msgname, tostring_r(msg))
    if agent then
        dbglog("send_msg=222==",uid, msgname, tostring_r(msg))
        skynet.send(agent, 'lua', "send_msg", msgname, msg)
    end    
end

-- --给指定玩家发个消息
-- function CMD.dispatch_activity_msg(msgname, msg)
--     for uid, agent in pairs(agents) do 
--         skynet.send(agent, 'lua', "dispatch_activity_msg", msgname, msg)
--     end
-- end


function CMD.get_enter_data(uid)
	local agent = agents[uid]
	if agent then
		local data = skynet.call(agent,'lua',uid,'get_enter_data')
		skynet.retpack(data)
	else
		errlog("CMD.get_enter_data agent is nil", uid)
	end
end

function CMD.money_change(uid,chg_tb)
	local agent = agents[uid]
	if agent then
		skynet.send(agent,'lua',uid,'notify_money_changed',chg_tb)
	end
end

function CMD.close_server()
	closing_sever = true
	skynet.sleep(500)  --睡眠5秒
	for uid,agent in pairs(agents) do
		skynet.send(agent,'lua','close_server')
	end
end

function CMD.stop_server()
	closing_sever = true
	skynet.sleep(500)  --睡眠5秒
	for uid,agent in pairs(agents) do
		skynet.send(agent,'lua','close_server')
	end
end

function CMD.gm(parma)
	print(tostring_r(parma))
	local cmd = parma.cmd
	local uid = tonumber(parma.uid)
	local value = parma.value
	local reason = reason.GM
	if cmd == "addcoins" then
        local ok,succ,ret = R().basesvr({key=uid}):call('.msg_handler','add_coins',uid,value,reason)
        local agent = agents[uid]
		if agent then
        	skynet.send(agent,'lua',uid,'notify_money_changed',{coins = ret.curr})
        end
    elseif cmd == "addgems" then
        local ok,succ,ret = R().basesvr({key=uid}):call('.msg_handler','add_gems',uid,value,reason)
        local agent = agents[uid]
		if agent then
        	skynet.send(agent,'lua',uid,'notify_money_changed',{gems = ret.curr})
        end
    elseif cmd == "addroomcards" then
        local ok,succ,curr_roomcards = R().basesvr({key=uid}):call('.msg_handler','add_roomcards',uid,value,reason)
        local agent = agents[uid]
		if agent then
        	skynet.send(agent,'lua',uid,'notify_money_changed',{roomcards = curr_roomcards})
        end
    end
end

function CMD.get_online_user_play_info()
    local play_info_list = {}
    for uid,agent in pairs(agents) do
        local data = {uid = uid,name = "test",coins = 0,game_type = 0,table_type = 0}
        local ret = skynet.call(agent,'lua',uid,'get_player_info')
        if ret then
            data.coins = ret.coins
            data.name  = ret.name 
        end

        local ok,table_gid = R().exdbsvr(1):call('.tlock_mgr','get_player_table',uid)
        if not ok or not table_gid then
            goto continue
        end

        if table_gid > 0 then
            local tsvr_id = utils.extract_table_gid(table_gid)
            local dest = R().tablesvr(tsvr_id):dest()
            local ok,succ,game_type,table_type = R().dest(dest):call('.table_mgr','get_game_type',table_gid)
            if not ok or not succ then
                goto continue
            end
            data.game_type  = game_type or 0
            data.table_type = table_type or 0
        end

        ::continue::

        table_insert(play_info_list,data)
    end

    skynet.retpack(play_info_list)
end

function CMD.common_post_data(url,data,uid)
    --dbglog(url,data,uid)
    skynet.retpack(common_post_web(uid or -1,url,data))
end

function CMD.change_icon(data)
    local uid = data.uid
    local icon = data.icon

    local agent = agents[uid]
    if agent then
        dbglog(uid,"change_iconchange_iconchange_iconchange_iconchange_icon",icon)
        skynet.send(agent,'lua',"change_icon",icon)
    end
    
    R().dbsvr{key=uid}:send('.msg_handler','change_icon',uid,icon)
end

function CMD.on_activity_start(data)
    dbglog("on_activity_start===",tostring_r(data))
    for uid,agent in pairs(agents) do
        if agent ~= 0 then
            skynet.send(agent,'lua',"on_activity_start",data)
        end
    end
end

function CMD.on_activity_end(data)
    dbglog("on_activity_end===",tostring_r(data))
    for uid,agent in pairs(agents) do
        if agent ~= 0 then
            skynet.send(agent,'lua',"on_activity_end",data)
        end
    end
end

function CMD.notify_to_all(pbname,ntf)
    for uid,agent in pairs(agents) do
        if agent ~= 0 then
            skynet.send(agent,'lua',uid,'send_notify',pbname,ntf)
        end
    end
end

function CMD.on_recharge(data)
    dbglog("on_recharge===",tostring_r(data))
    local uid = data.uid
    if agents[uid] and agents[uid] ~= 0 then
        skynet.send(agents[uid],'lua',"on_recharge",data)
    end
end

function CMD.on_return_water_arward(data)
    dbglog("on_return_water_arward===",tostring_r(data))
    local uid = data.uid
    if agents[uid] and agents[uid] ~= 0 then
        skynet.send(agents[uid],'lua',"on_return_water_arward",data)
    else
        local water = math_floor(data.water)
        local str_date = os.date("%Y/%m/%d",data.time)
        local water_award = global_configs.water_award
        if not water_award then return end
        for _,v in pairs(water_award) do
            if v.min_water <= water and (not v.max_water or water <= v.max_water) then
                local coins = math_floor(water * v.rate / 100)
                local exinfo = player:get_extra_bill_info() --{channel = player.channel,cur_channel = player.cur_channel}
                local ok,succ,ret = R().basesvr({key=uid}):call('.msg_handler','add_coins',uid,coins,reason.WATER_RETRUN,{})
                if ok and succ and ret then
                   notify_money_changed(uid,{coins = ret.curr})
                end

                local mail_list = {}
                local mail = {}
                mail.uid = uid
                mail.title = string.format(mail_def.BACK_WATER_TITLE,str_date)
                mail.content = string.format(mail_def.BACK_WATER_CONTENT,str_date,water/100,coins/100)
                mail.coins = 0
                mail.mail_type = 2
                mail.op_user = mail_def.OP_USER
                table_insert(mail_list,mail)

                print("send_back_water=========",tostring_r(mail_list))
                local url = constant.ADD_MAIL_URL
                R().hallsvr(1):send('.msg_handler','common_post_data',url,{award_list = mail_list})
                break
            end
        end

        local data = {}
        data.uid = uid
        data.type = constant.DODULE_ID.DAY_REBATE  
        data.key = ""..os.date("%Y%m%d%H%M%S") .."_".. data.type .. "_" .. math.random(1,10000)
        data.op = "partake_num"
        dbglog("_____opPartakeNum__", dump(data))

        billlog(data)
    end
end

function CMD.add_person_water(data)
    dbglog("add_person_water===",tostring_r(data))
    local uid = data.uid
    if agents[uid] and agents[uid] ~= 0 then
        skynet.send(agents[uid],'lua',"add_person_water",data)
    end
end

--首充流水
function CMD.add_shouchong_water(data)
    dbglog("add_shouchong_water===",data)
    local uid = data.uid
    if agents[uid] and agents[uid] ~= 0 then
        skynet.send(agents[uid],'lua',"add_shouchong_water", data)
    end
end

--首充
function CMD.add_recharge(data)
    dbglog("add_recharge===",data)
    local uid = data.uid
    if agents[uid] and agents[uid] ~= 0 then
        skynet.send(agents[uid],'lua',"add_recharge", data)
    else
        --玩家不在线的情况
        --判断是否够xxx，够就改变首充状态（0没有充值达xxx， 1充值达xxx，2已发送奖励
        local uid = data.uid
        local coins = data.coins
        local sc_conf = global_configs.shouchong.ac_content    
        print("____addRecharge___", sc_conf)
        if coins >= sc_conf.charge_target then             
            --改变状态为1
            local server = R().basesvr({key=uid})
            server:send('.msg_handler', 'update_first_charge_status', uid, 1)
        end
    end
end

function CMD.on_vip_update(uid,vip_lv,person_water)
    dbglog(uid,"on_vip_update:",vip_lv,person_water)
    if agents[uid] and agents[uid] ~= 0 then
        skynet.send(agents[uid],'lua',"on_vip_update",vip_lv,person_water)
    end
end

--修改用户属性
--data={name="xxx",}
function CMD.change_property(uid, data)
    local agent = agents[uid]
    if not agent then
        errlog('could not find player',uid)
        skynet.retpack(nil)
        return
    end

    skynet.send(agent, 'lua', "change_property", data)
    skynet.retpack(true)
end





---------------------------------------------------------------------------





function dispatch_cmd(session,source,action,...)
    local f = assert(CMD[action],'unknown cmd ' .. action)
    f(...)
end

function start()
    skynet.register_protocol {
        name = "client",
        id = skynet.PTYPE_CLIENT,
        pack = proxypack.pack_raw
    }
    skynet.start(function()
        skynet.dispatch("lua", function(session, source, action, ...)
            dbglog('============got params ...... ',action,...)
            dispatch_cmd(session,addr,action,...)
        end)

        global_configs = setmetatable({},{
            __index = function(t,k) 
                return sharedata.query(k)
            end
        })
        _ENV.global_configs = global_configs
    end)    
end

_START(function()
    print('now this service is starting')
    init()
    start()
end)

